import axios from 'axios'
import {Message} from 'element-ui'
import {showLoading, hideLoading} from '../loading/index'
import de from "element-ui/src/locale/lang/de";
import router from "../router";
//响应时间
axios.defaults.timeout = 6 * 10000
//配置cookie
// axios.defaults.withCredentials = true;
//配置请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
//
axios.defaults.baseURL = 'http://172.16.110.61:7060'

//发布环境
// axios.defaults.baseURL = 'http://47.102.213.255:7060'
var loadingInstance
//（添加请求拦截器）
axios.interceptors.request.use(
  config => {
    showLoading();
    let token = sessionStorage.getItem("token");
    if (token) {
      config.headers.Authorization = sessionStorage.getItem('token')
    }
    return config;
  },
  err => {
    hideLoading();
    Message.error('请求错误')
    return Promise.reject(err)
  }
)

//（添加响应拦截器）
axios.interceptors.response.use(

  response => {
    hideLoading();
    return response;
  },
  err => {
    hideLoading();
    let that = this;
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          Message.error('错误请求')
          break;
        case 401:
          sessionStorage.setItem("token" , '');
          router.replace('/login')
          break;
        case 403:
          Message.error('拒绝访问')
          break;
        case 404:
          Message.error('请求错误,未找到该资源')
          break;
        case 405:
          Message.error('请求方法未允许')
          break;
        case 408:
          Message.error('请求超时')
          break;
        case 500:
          Message.error('服务器端出错,请联系管理员')
          break;
        case 501:
          Message.error('网络未实现')
          break;
        case 502:
          Message.error('网络错误')
          break;
        case 503:
          Message.error('服务不可用')
          break;
        case 504:
          Message.error('网络超时')
          break;
        case 505:
          Message.error('http版本不支持该请求')
          break;
        default:
          Message.error(`连接错误${err.response.status}`)
      }
    } else{
      console.log(err)
      Message.error('连接到服务器失败')
    }
    return Promise.reject(err);
  }
)

// 发送post请求
export function post(url, params) {

  return new Promise((resolve, reject) => {
    axios
      .post(url, params)
      .then(
        res => {
          resolve(res.data)
        },
        err => {
          reject(err.data)
        }
      )
      .catch(err => {
        reject(err.data)
      })
  })
}

// 发送get请求
export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params
      })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err.data)
      })
  })
}
